﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Transactions;
using System.Net.Mail;
using System.Configuration;
using LeadVinaglue.Models;
using LeadVinaglue.Repository;

namespace LeadVinaglue.Utility
{
    public class UserEmailToken
    {
        // Send an email when user register success
        // Handle exception when failure
        public static bool SendEmail(User model, string emailType, ref bool success)
        {
            string websiteURL = ConfigurationSettings.AppSettings["WebsiteURL"].ToString();
            string fromEmailAddress = ConfigurationSettings.AppSettings["FromEmailAddress"].ToString();

            System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
            System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(fromEmailAddress);

            // Get email template
            var template = new EmailTemplateRepository().GetSingle(emailType);

            if (template != null)
            {
                // Build a content
                string body = string.Empty;
                body = template.Body;
                body = body.Replace("[FULLNAME]", model.Email);
                body = body.Replace("[EMAIL]", model.Email);
                body = body.Replace("[LINKACTIVE]", string.Format("<a href='{0}/Account/Activate?guid={1}&email={2}' target='_blank'>Kích hoạt</a>", websiteURL, model.GUID, model.Email));
                body = body.Replace("[LINKDEACTIVE]", string.Format("<a href='{0}/Account/DeActivate?guid={1}&email={2}' target='_blank'>Hủy bỏ</a>", websiteURL, model.GUID, model.Email));

                // Assign email object to information of this contact.
                email.Subject = template.SubjectLine;
                email.To.Add(model.Email);
                email.From = from;
                email.IsBodyHtml = true;
                email.Body = body;

                //put this in a transaction
                using (TransactionScope scope = new TransactionScope())
                {
                    try
                    {
                        SmtpClient smtpClient = new SmtpClient();

                        if (ConfigurationSettings.AppSettings["SmtpHostValue"] != null)
                        {
                            smtpClient.Host = ConfigurationSettings.AppSettings["SmtpHostValue"].ToString();
                        }
                        else
                        {
                            smtpClient.Host = "";
                        }

                        if (ConfigurationSettings.AppSettings["SmtpPortValue"] != null)
                        {
                            smtpClient.Port = int.Parse(ConfigurationSettings.AppSettings["SmtpPortValue"].ToString());
                        }
                        else
                        {
                            smtpClient.Port = 25;
                        }

                        smtpClient.Send(email);

                        //end transaction
                        scope.Complete();

                        //assign status
                        return true;
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                }
            }

            return false;
        }

        // Send an email when user forgot password
        // Handle exception when failure
        public static bool SendEmail(string userEmail, string emailType, ref bool success)
        {
            string fromEmailAddress = ConfigurationSettings.AppSettings["FromEmailAddress"].ToString();

            System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
            System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(fromEmailAddress);

            // Get email template
            var template = new EmailTemplateRepository().GetSingle(emailType);
            UserRepository uRepository = new UserRepository();
            var user = uRepository.GetSingle(userEmail);

            if (template != null && user != null)
            {
                // Get user Info
                string password = new Random().Next(100000, 999999).ToString();
                user.Password = EncryptionData.Encryption(password);
                
                uRepository.Save(user);
                    
                // Build a content
                string body = string.Empty;
                body = template.Body;
                body = body.Replace("[FULLNAME]", user.Fullname);
                body = body.Replace("[EMAIL]", userEmail);
                body = body.Replace("[PASSWORD]", password);

                // Assign email object to information of this contact.
                email.Subject = template.SubjectLine;
                email.To.Add(userEmail);
                email.From = from;
                email.IsBodyHtml = true;
                email.Body = body;

                //put this in a transaction
                using (TransactionScope scope = new TransactionScope())
                {
                    try
                    {
                        SmtpClient smtpClient = new SmtpClient();

                        if (ConfigurationSettings.AppSettings["SmtpHostValue"] != null)
                        {
                            smtpClient.Host = ConfigurationSettings.AppSettings["SmtpHostValue"].ToString();
                        }
                        else
                        {
                            smtpClient.Host = "";
                        }

                        if (ConfigurationSettings.AppSettings["SmtpPortValue"] != null)
                        {
                            smtpClient.Port = int.Parse(ConfigurationSettings.AppSettings["SmtpPortValue"].ToString());
                        }
                        else
                        {
                            smtpClient.Port = 25;
                        }

                        smtpClient.Send(email);

                        //end transaction
                        scope.Complete();

                        //assign status
                        return true;
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                }
            }

            return false;
        }

        // Send an email when user contact to raovat24.net
        // Handle exception when failure
        public static bool SendEmail(Contact contact, string emailType, ref bool success)
        {
            string websiteURL = ConfigurationSettings.AppSettings["WebsiteURL"].ToString();
            string fromEmailAddress = ConfigurationSettings.AppSettings["FromEmailAddress"].ToString();

            System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
            System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(fromEmailAddress);

            // Get email template
            var template = new EmailTemplateRepository().GetSingle(emailType);

            if (template != null)
            {
                // Build a content
                string body = string.Empty;
                body = template.Body;
                body = body.Replace("[FULLNAME]", contact.Name);
                body = body.Replace("[EMAIL]", contact.Email);
                body = body.Replace("[PHONE]", contact.Phone);
                body = body.Replace("[MESSAGE]", contact.Message);

                // Assign email object to information of this contact.
                email.Subject = template.SubjectLine;
                email.To.Add(contact.Email);
                email.From = from;
                email.IsBodyHtml = true;
                email.Body = body;

                //put this in a transaction
                using (TransactionScope scope = new TransactionScope())
                {
                    try
                    {
                        SmtpClient smtpClient = new SmtpClient();

                        if (ConfigurationSettings.AppSettings["SmtpHostValue"] != null)
                        {
                            smtpClient.Host = ConfigurationSettings.AppSettings["SmtpHostValue"].ToString();
                        }
                        else
                        {
                            smtpClient.Host = "";
                        }

                        if (ConfigurationSettings.AppSettings["SmtpPortValue"] != null)
                        {
                            smtpClient.Port = int.Parse(ConfigurationSettings.AppSettings["SmtpPortValue"].ToString());
                        }
                        else
                        {
                            smtpClient.Port = 25;
                        }

                        smtpClient.Send(email);

                        //end transaction
                        scope.Complete();

                        //assign status
                        return true;
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                }
            }

            return false;
        }


        // Send an email to user
        // Handle exception when failure
        public static void SendEmailNotice(string userEmail, EmailTemplate model, ref string message, ref bool success)
        {
            string fromEmailAddress = ConfigurationSettings.AppSettings["FromEmailAddress"].ToString();

            System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
            System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(fromEmailAddress);

            if (model != null)
            {
                // Build a content
                string body = string.Empty;
                body = model.Body;
                body = body.Replace("[EMAIL]", userEmail);

                // Assign email object to information of this contact.
                Random r = new Random();
                email.Subject = string.Format("#{0} -{1}", r.Next(10000, 99999), model.SubjectLine);
                email.To.Add(userEmail);
                email.From = from;
                email.IsBodyHtml = true;
                email.Body = body;

                //put this in a transaction
                using (TransactionScope scope = new TransactionScope())
                {
                    try
                    {
                        SmtpClient smtpClient = new SmtpClient();

                        if (ConfigurationSettings.AppSettings["SmtpHostValue"] != null)
                        {
                            smtpClient.Host = ConfigurationSettings.AppSettings["SmtpHostValue"].ToString();
                        }
                        else
                        {
                            smtpClient.Host = "";
                        }

                        if (ConfigurationSettings.AppSettings["SmtpPortValue"] != null)
                        {
                            smtpClient.Port = int.Parse(ConfigurationSettings.AppSettings["SmtpPortValue"].ToString());
                        }
                        else
                        {
                            smtpClient.Port = 25;
                        }

                        smtpClient.Send(email);

                        //end transaction
                        scope.Complete();

                        //assign status
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        message = ex.Message;
                        success = false;
                    }
                }
            }

            success = false;
        }
    }
}